<template>
  <div class="product-management-container">
    <div class="header-actions">
      <h2>商品管理</h2>
      <el-button type="primary" icon="el-icon-plus" @click="handleAddProduct">添加商品</el-button>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="输入商品名称搜索"
        prefix-icon="el-icon-search"
        style="width: 300px;"
        @keyup.enter.native="fetchProducts"
      ></el-input>
      <el-select v-model="categoryId" placeholder="选择分类" style="width: 180px; margin-left: 10px;">
        <el-option value="" label="全部分类"></el-option>
        <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
      </el-select>
      <el-select v-model="brandId" placeholder="选择品牌" style="width: 180px; margin-left: 10px;">
        <el-option value="" label="全部品牌"></el-option>
        <el-option v-for="brand in brands" :key="brand.id" :label="brand.name" :value="brand.id"></el-option>
      </el-select>
      <el-button type="primary" @click="fetchProducts" style="margin-left: 10px;">搜索</el-button>
      <el-button @click="resetSearch" style="margin-left: 10px;">重置</el-button>
    </div>

    <div class="table-container">
      <el-table
        :data="productList"
        style="width: 100% !important; height: 100% !important;"
        border
        stripe
        :header-cell-style="{ 'background': 'linear-gradient(90deg, #3b82f6 0%, #60a5fa 100%)', 'color': 'white', 'font-weight': 'bold', 'border-radius': '4px 4px 0 0' }"
        :row-class-name="tableRowClassName"
        :row-style="{ 'transition': 'background-color 0.2s' }"
        :cell-style="{ 'padding': '12px', 'border-radius': '4px' }"
        fit
        v-loading="loading"
        @row-mouse-enter="handleRowMouseEnter"
        @row-mouse-leave="handleRowMouseLeave"
      >
      <el-table-column prop="spuId" label="ID" width="60"></el-table-column>
      <el-table-column prop="spuName" label="商品名称" width="180"></el-table-column>
      <el-table-column prop="brandName" label="品牌" min-width="100" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="categoryName" label="分类" min-width="100" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="unitPrice" label="价格" min-width="90" :show-overflow-tooltip="true">
        <template slot-scope="scope">{{ scope.row.unitPrice | formatPrice }}</template>
      </el-table-column>
      <el-table-column prop="unit" label="单位" min-width="80" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="salesCount" label="销量" min-width="100" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="status" label="状态" min-width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="(val) => handleStatusChange(scope.row.spuId, val)"
            :active-text="'上架'"
            :inactive-text="'下架'"
            active-color="#4caf50"
            inactive-color="#f44336"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="140" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEditProduct(scope.row)">编辑</el-button>
          <el-button type="info" size="small" @click="handleViewDetails(scope.row.spuId)" style="margin-left: 5px;">详情</el-button>
        </template>
      </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        :pager-count="5"
      ></el-pagination>
    </div>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" width="60%" :center="true">
      <el-form :model="productForm" ref="productForm" :rules="formRules" label-width="120px">
        <el-form-item label="商品名称" prop="spuName">
          <el-input v-model="productForm.spuName" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" v-model="productForm.description" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="productForm.brandId" placeholder="请选择品牌">
            <el-option v-for="brand in brands" :key="brand.id" :label="brand.name" :value="brand.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="productForm.categoryId" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品单价" prop="unitPrice">
          <el-input v-model.number="productForm.unitPrice" placeholder="请输入商品单价"></el-input>
        </el-form-item>
        <el-form-item label="计量单位" prop="unit">
          <el-input v-model="productForm.unit" placeholder="请输入计量单位"></el-input>
        </el-form-item>
        <el-form-item label="商品主图" prop="mainImage">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="handleImageUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <img v-if="productForm.mainImage" :src="productForm.mainImage" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProductList, updateProductStatus, addProduct, updateProduct, getProductDetail, uploadProductImage } from '../api/productApi';
import { getCategories, getBrands } from '../api/commonApi';

export default {
  name: 'ProductManagement',
  data() {
    return {
      productList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      searchKeyword: '',
      categoryId: '',
      brandId: '',
      dialogVisible: false,
      dialogTitle: '添加商品',
      productForm: {
        spuId: null,
        spuName: '',
        description: '',
        categoryId: '',
        brandId: '',
        unitPrice: null,
        unit: '',
        mainImage: '',
        status: 1
      },
      brands: [],
      categories: [],
      formRules: {
        spuName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
        brandId: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
        unitPrice: [
          { required: true, message: '请输入商品单价', trigger: 'blur' },
          { type: 'number', min: 0, message: '单价不能小于0', trigger: 'blur' }
        ],
        unit: [{ required: true, message: '请输入计量单位', trigger: 'blur' }]
      }
    };
  },
  mounted() {
    this.fetchProducts();
    this.loadBrands();
    this.loadCategories();
  },
  methods: {
    fetchProducts() {
      this.loading = true;
      getProductList(this.pageNum, this.pageSize, this.searchKeyword, this.categoryId, this.brandId)
        .then(response => {
          console.log("获取商品列表响应:",response);
          // 添加空值检查防止null引用错误
          if (response && response.data) {
            this.productList = response.data.records || [];
            this.total = response.data.total || 0;
            this.loading = false;
          } else {
            this.productList = [];
            this.total = 0;
            this.loading = false;
            this.$message.warning('返回数据格式不正确');
          }
        })
        .catch(error => {
          this.$message.error('获取商品列表失败: ' + error.message);
        });
    },
    handleStatusChange(spuId, status) {
      updateProductStatus(spuId, status)
        .then((resqponse) => {
          console.log("更新商品状态响应: ",resqponse);
          if(resqponse.code === 0) {
            this.$message.success('商品状态更新成功');
            this.fetchProducts();
          } else {
            this.$message.error(resqponse.msg);
            // 失败时恢复原状态
            this.fetchProducts();
          }
        })
        .catch(error => {
          // 检查是否是审核未通过的错误
          if (error.message && error.message.includes('审核未通过')) {
            this.$message.error('审核未通过，无法更新商品状态');
          } else {
            this.$message.error('商品状态更新失败: ' + error.message);
          }
          // 失败时恢复原状态
          this.fetchProducts();
        });
    },
    handleAddProduct() {
      this.dialogTitle = '添加商品';
      this.productForm = {
        spuId: null,
        spuName: '',
        description: '',
        categoryId: '',
        brandId: '',
        unitPrice: null,
        unit: '',
        mainImage: '',
        status: 1
      };
      this.dialogVisible = true;
    },
    handleEditProduct(row) {
      this.dialogTitle = '编辑商品';
      getProductDetail(row.spuId)
        .then(response => {
          // 添加空值检查防止null引用错误
          if (response && response.data) {
            this.productForm = response.data;
            this.dialogVisible = true;
          } else {
            this.$message.error('获取商品详情失败: 返回数据格式不正确');
          }
        })
        .catch(error => {
          this.$message.error('获取商品详情失败: ' + error.message);
        });
    },
    handleViewDetails(spuId) {
      // 查看详情逻辑
      this.$router.push({ path: `/product/detail/${spuId}` });
    },
    submitForm() {
      this.$refs.productForm.validate(valid => {
        if (valid) {
          if (this.productForm.spuId) {
            // 编辑商品
            updateProduct(this.productForm)
              .then(() => {
                this.$message.success('商品更新成功');
                this.dialogVisible = false;
                this.fetchProducts();
              })
              .catch(error => {
                this.$message.error('商品更新失败: ' + error.message);
              });
          } else {
            // 添加商品
            addProduct(this.productForm)
              .then(() => {
                this.$message.success('商品添加成功');
                this.dialogVisible = false;
                this.fetchProducts();
              })
              .catch(error => {
                this.$message.error('商品添加失败: ' + error.message);
              });
          }
        }
      });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchProducts();
    },
    handleCurrentChange(page) {
      this.pageNum = page;
      this.fetchProducts();
    },
    resetSearch() {
      this.searchKeyword = '';
      this.categoryId = '';
      this.brandId = '';
      this.pageNum = 1;
      this.fetchProducts();
    },
    loadBrands() {
      getBrands({})
        .then(response => {
          // 处理不同响应格式，确保数据存在
          const brandData = response.data || response;
          if (Array.isArray(brandData)) {
            this.brands = brandData.map(brand => ({
              id: brand.brandId,
              name: brand.brandName
            }));
          } else {
            this.$message.error('品牌数据格式不正确');
          }
        })
        .catch(error => {
          this.$message.error('获取品牌列表失败: ' + error.message);
        });
    },
    loadCategories() {
      getCategories()
        .then(response => {
          // 处理不同响应格式，确保数据存在
          const categoryData = response.data || response;
          if (Array.isArray(categoryData)) {
            this.categories = categoryData.map(category => ({
              id: category.categoryId,
              name: category.categoryName
            }));
          } else {
            this.$message.error('分类数据格式不正确');
          }
        })
        .catch(error => {
          this.$message.error('获取分类列表失败: ' + error.message);
        });
    },
    handleImageSuccess(response, file) {
      this.productForm.mainImage = URL.createObjectURL(file.raw);
    },
    handleImageUpload(options) {
      const file = options.file;
      uploadProductImage(file)
        .then(response => {
          // 正确解析后端返回的JsonData结构
          // 灵活判断图片上传成功，优先检查data是否存在且是有效URL
            // 根据用户反馈，URL在msg字段中
            if (response.msg) {
              // 检查返回的msg是否是有效的URL
              const isUrl = /^https?:\/\/.+\.(png|jpg|jpeg|gif|bmp)$/i.test(response.msg);
              if (isUrl) {
                this.productForm.mainImage = response.msg;
                options.onSuccess(response);
                this.$message.success('图片上传成功');
              } else {
                options.onError(new Error('返回的图片URL格式无效'));
                this.$message.error('图片上传失败: 返回的URL格式无效');
              }
            } else {
              options.onError(new Error('返回的图片URL不存在'));
              this.$message.error('图片上传失败: 返回的URL不存在');
            }
        })
        .catch(error => {
          options.onError(error);
          this.$message.error('图片上传失败: ' + (error.message || '未知错误'));
        });
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.error('上传文件必须是图片格式!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过5MB!');
        return false;
      }
      return true;
    },
    tableRowClassName({rowIndex}) {
      return rowIndex % 2 === 0 ? 'warning-row' : 'success-row';
    },
    
    // 行悬停效果
    handleRowMouseEnter(row, event) {
      event.currentTarget.style.backgroundColor = '#f0f7ff';
      event.currentTarget.style.transition = 'background-color 0.2s';
    },
    
    handleRowMouseLeave(row, event) {
      // 恢复原来的颜色
      const rowIndex = this.productList.indexOf(row);
      event.currentTarget.style.backgroundColor = rowIndex % 2 === 0 ? '#f9f9f9' : '#ffffff';
    },
  },
  filters: {
    formatPrice(price) {
      return '¥' + (price || 0).toFixed(2);
    }
  }
};
</script>

<style scoped>
.product-management-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  flex-direction: column;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  background: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 20px;
      padding-top: 15px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      padding: 15px;
      width: 100% !important;
      box-sizing: border-box;
    }

.el-table__header-wrapper,
.el-table__body-wrapper,
.el-table__footer-wrapper {
  width: 100% !important;
  height: 100% !important;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  table-layout: fixed;
}

/* 表格行悬停效果 */
::v-deep .el-table__body tr:hover > td {
  background-color: #f0f7ff !important;
  transition: background-color 0.2s;
}

/* 表格单元格样式 */
::v-deep .el-table__cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 8px 12px;
}

/* 分页样式 */
::v-deep .el-pagination {
  display: flex;
  justify-content: flex-end;
}

/* 按钮样式优化 */
::v-deep .el-button--primary {
  background: linear-gradient(90deg, #2563eb 0%, #3b82f6 100%);
  border: none;
}

::v-deep .el-button--primary:hover {
  background: linear-gradient(90deg, #1d4ed8 0%, #2563eb 100%);
}

::v-deep .el-button--success {
  background: linear-gradient(90deg, #10b981 0%, #34d399 100%);
  border: none;
}

::v-deep .el-button--success:hover {
  background: linear-gradient(90deg, #059669 0%, #10b981 100%);
}

/* 加载动画样式 */
::v-deep .el-loading-spinner {
  top: 50%;
  transform: translateY(-50%);
}

/* 隐藏滚动条 */
::v-deep .el-table__body-wrapper {
  overflow-y: auto;
  scrollbar-width: none; /* Firefox */
}

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  display: none; /* Chrome, Safari, Edge */
}

::v-deep .el-table__body-wrapper::-moz-scrollbar {
  display: none; /* Firefox */
}

.avatar-uploader .el-upload {
  border: 1px dashed #c7d2fe;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #3b82f6;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #60a5fa;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 6px;
}

.el-table .warning-row {
  background: #f0f9ff;
}

.el-table .success-row {
  background: #ecfdf5;
}
.el-switch__label * {
  display: inline-block;
  padding: 0 5px;
  font-size: 12px;
}
html{
  height: 100%;
  width: 100%;
  overflow: hidden;
}
body{
  height: 100%;
  width: 100%;
  overflow: hidden;
}
</style>